/*
 * @Author: 吴世扬 18368095041@163.com
 * @Date: 2024-08-27 16:34:31
 * @LastEditors: 吴世扬 18368095041@163.com
 * @LastEditTime: 2024-09-26 08:01:46
 * @FilePath: /react18-vite-admin/src/views/login/LoginView.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import { useState, useEffect } from 'react';
import {
    UserOutlined,
    LockOutlined,
    SafetyCertificateOutlined
} from '@ant-design/icons';
import { Switch, Tag, Card, Form, Input, Tooltip, Image, Button } from 'antd';
import { immerable } from 'immer';
import { useImmer } from 'use-immer';
import { useTranslation } from 'react-i18next';

import LangSelect from '@/components/ui/LangSelect/LangSelect';
import LogoUrl from '@/assets/images/logo.png';
import defaultSettings from '@/settings';
import { getCaptchaUrl } from '@/api/login';
import { usePermissionStore, useSettingsStore } from '@/store';
import { useRules } from '@/service/useRules';
import { useLogin } from '@/service/biz/useLogin';
import { useUser } from '@/store';

import './LoginView.global.scss';
import './LoginView.scoped.scss';

class LoginData {
    [immerable] = true;
    username = '';
    password = '';
    captcha = '';
}

const LoginView = () => {
    const { requiredRule } = useRules();
    const { t } = useTranslation();

    const { themeMode, setThemeMode } = useSettingsStore((state) => state);
    const { setNeedUpdate } = usePermissionStore(state => state);

    const [loginData, setLoginData] = useImmer(new LoginData());

    const [captchaBase64, setCaptchaBase64] = useState('');

    const getCaptcha = () => {
        setCaptchaBase64(getCaptchaUrl());
    };

    const [isCapslock, setIsCapslock] = useState(false);

    const { loginLoading, login, tokenRef } = useLogin();
    const { loginByToken } = useUser();

    const handleLogin = async () => {
        await login(loginData);
        setNeedUpdate(true);
        loginByToken(tokenRef.current);
    };

    useEffect(() => {
        getCaptcha();
    }, []);

    return (
        <div className="loginview-container">
            <div className="absolute-lt flex-x-end p-3 w-full z-10">
                <Switch
                    checked={themeMode === 'default'}
                    onChange={(e) => setThemeMode(e ? 'default' : 'dark')}
                ></Switch>

                <LangSelect className="ml-2 c-primary dark:c-text" ></LangSelect>
            </div>

            <div className="absolute inset-t-0 mx-auto mt-[30px] flex flex-row items-center z-10">
                <img src={LogoUrl} className="w-[100px] h-p[100px]" />
                <div className="flex flex-row items-start">
                    <span className="c-[#0777FF] text-6xl dark:c-text">
                        {t('app.title')}
                    </span>
                    <Tag className="ml-2" color="orange">
                        {defaultSettings.version}
                    </Tag>
                </div>
            </div>

            <Card className="!border-none !rounded-4% w-100 <sm:w-85 z-10">
                <Form className={'login-form'}>
                    <Form.Item rules={requiredRule}>
                        <div className="flex-y-center w-full">
                            <Input
                                value={loginData.username}
                                name="username"
                                placeholder={t('login.username')}
                                size="large"
                                prefix={<UserOutlined className="c-text1" />}
                                onChange={(event) => {
                                    const value = event.target.value;
                                    setLoginData((draft) => {
                                        draft.username = value;
                                    });
                                }}
                            ></Input>
                        </div>
                    </Form.Item>

                    <Tooltip
                        placement="right"
                        open={isCapslock}
                        title={t('login.capsLock')}
                    >
                        <Form.Item rules={requiredRule}>
                            <Input.Password
                                value={loginData.password}
                                name="username"
                                placeholder={t('login.password')}
                                size="large"
                                prefix={<LockOutlined className="c-text1" />}
                                onChange={(event) => {
                                    console.log(event.target.value);
                                    setLoginData((draft) => {
                                        draft.password = event.target.value;
                                    });
                                }}
                                onBlur={() => {
                                    setIsCapslock(false);
                                }}
                                onKeyDown={(event) => {
                                    setIsCapslock(
                                        event.getModifierState('CapsLock')
                                    );
                                }}
                                onKeyUp={(event) => {
                                    setIsCapslock(
                                        event.getModifierState('CapsLock')
                                    );
                                    if (event.key === 'Enter') {
                                        handleLogin();
                                    }
                                }}
                            ></Input.Password>
                        </Form.Item>
                    </Tooltip>

                    <Form.Item rules={requiredRule}>
                        <Input
                            className="capcha-input"
                            value={loginData.captcha}
                            prefix={
                                <SafetyCertificateOutlined className="c-text1" />
                            }
                            placeholder={t('login.captchaCode')}
                            addonAfter={
                                <Image
                                    src={captchaBase64}
                                    preview={false}
                                    width="120px"
                                    height="38px"
                                    onClick={getCaptcha}
                                    className="cursor-pointer"
                                ></Image>
                            }
                            size="large"
                            onChange={(event) => {
                                setLoginData((draft) => {
                                    draft.captcha = event.target.value;
                                });
                            }}
                            onKeyUp={(event) => {
                                if (event.key === 'Enter') {
                                    handleLogin();
                                }
                            }}
                        ></Input>
                    </Form.Item>

                    <Button
                        type="primary"
                        size="large"
                        className="w-full"
                        loading={loginLoading}
                        onClick={handleLogin}
                    >
                        登录
                    </Button>
                </Form>
            </Card>
        </div>
    );
};

export default LoginView;
